package com.yx.edu.controller;

import com.yx.edu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

//加入ioc容器
@Controller
//设置请求路径
@RequestMapping("/demo")
public class DemoController {

    //设置请求路径
    @RequestMapping("/handle01")
    public ModelAndView handle01() {
        Date date = new Date();// 服务器时间
        // 返回服务器时间到前端页面
        // 封装了数据和页面信息的 ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // addObject 其实是向请求域中request.setAttribute("date",date);
        modelAndView.addObject("date", date);
        // 视图信息(封装跳转的页面信息) 逻辑视图名
        modelAndView.setViewName("success");
        //打印ModelAndView
        //System.out.println("modelAndView: " + modelAndView.getClass());
        System.out.println("handler方法执行了 ===============");
        return modelAndView;
    }

    //使用modelMap传递数据
    @RequestMapping("/handle02")
    public String handle02(ModelMap modelMap) {
        Date date = new Date();
        modelMap.addAttribute("date", date);
        System.out.println("modelMap: " + modelMap.getClass());
        return "success";
    }

    //使用model传递数据
    @RequestMapping("/handle03")
    public String handle03(Model model) {
        Date date = new Date();
        model.addAttribute("date", date);
        System.out.println("model: " + model.getClass());
        return "success";
    }

    //使用map集合传递数据
    @RequestMapping("/handle04")
    public String handle04(Map<String, Object> map) {
        Date date = new Date();
        map.put("date", date);
        System.out.println("map: " + map.getClass());
        return "success";
    }

    // /demo/handle/15
    @RequestMapping(value = "/handle/{id}", method = {RequestMethod.DELETE})
    public String handle(@PathVariable("id") Integer id) {
        System.out.println(id);
        Date date = new Date();
        return "success";
    }

    //配置了@ResponseBody,就不再走视图解析器了,而是直接等于response输出数据
    @ResponseBody
    @RequestMapping(value = "handle20", method = {RequestMethod.POST})
    public User handle20(@RequestBody User user) {
        System.out.println(user);
        user.setAge(15);
        return user;
    }

    @RequestMapping("upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request)
            throws IOException {
        // ⽂件原名，如xxx.jpg
        String originalFilename = uploadFile.getOriginalFilename();
        // 获取⽂件的扩展名,如jpg
        String extendName =
                originalFilename.substring(originalFilename.lastIndexOf(".") + 1,
                        originalFilename.length());
        String uuid = UUID.randomUUID().toString();
        // 新的⽂件名字
        String newName = uuid + "." + extendName;
        String realPath =
                request.getSession().getServletContext().getRealPath("/uploads");
        // 解决⽂件夹存放⽂件数量限制，按⽇期存放
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File floder = new File(realPath + "/" + datePath);
        if (!floder.exists()) {
            floder.mkdirs();
        }
        uploadFile.transferTo(new File(floder, newName));
        return "success";
    }

    /*//指定捕获异常的类型
    @ExceptionHandler(Exception.class)
    //可以将捕获的异常类型或父类当成方法形参传入
    public ModelAndView handlerException(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("msg", e.getMessage());
        return modelAndView;
    }*/

    @RequestMapping("exception")
    public String exception() {
        int i = 1 / 0;
        System.out.println("异常测试---");
        return "success";
    }

    /**
     * 重定向时,url会发生改变,原先get拼接的参数会导致丢失
     *
     * @param name
     * @return
     */
    @RequestMapping("handleRedirect")
    public String handleRedirect(@RequestParam("name") String name, RedirectAttributes redirectAttributes) {
        System.out.println("进行重定向");
        //携带参数⻓度有限制参数安全性也不⾼
        //return "redirect:handle10?name=" + name;


        // addFlashAttribute⽅法设置了⼀个flash类型属性，该属性会被暂存到session中，在跳转到⻚⾯之后该属性销毁
        redirectAttributes.addFlashAttribute("name", name);
        return "redirect:handle10";
    }

    /**
     * 重定向的handle方法
     *
     * @param name
     * @return
     */
    @RequestMapping("handle10")
    //使用接收参数@ModelAttribute("name")
    public ModelAndView handle10(@ModelAttribute("name") String name) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("success");
        modelAndView.addObject("name", name);
        return modelAndView;
    }
}
